package com.kadron.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.ItemSize;
import com.kadron.entity.Size;

@AutoCreate
@BypassInterceptors
@Name("itemSizeDAO")
public class KItemSizeDAO extends KDAO<ItemSize> {

	private static final Log LOG = LogFactory.getLog(KItemSizeDAO.class);
	
	public ItemSize find(long itId, long sizeId) {
		EntityManager em = getEntityManager();
		try {
			return (ItemSize) em.createQuery("SELECT e FROM ItemSize e WHERE e.item.id = :it_id AND e.size.id = :size_id ")
			.setParameter("it_id", itId)
			.setParameter("size_id", sizeId)
			.getSingleResult();			
		} catch (NoResultException e) {
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<ItemSize> getItemSize(long itId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT DISTINCT p FROM ItemSize p WHERE " +
				"p.item.id = :it_id ")
		.setParameter("it_id", itId)
		.getResultList();
	}
	
	public Integer delete(long itId, List<Size> list) {
		if (list == null || list.isEmpty()) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("CALL delete with empty list!");
			}
			return null;
		}
		EntityManager em = getEntityManager();
		Integer exec = null;
		try {
			 exec = em.createQuery("DELETE FROM ItemSize WHERE item.id = :it_id AND size in (:list) ")
			.setParameter("it_id", itId)
			.setParameter("list", list)
			.executeUpdate();			
		} catch (HibernateException e) {
			if (LOG.isErrorEnabled()) {
				LOG.error("HibernateException on delete, "+e);
			}
		}
		return exec;
	}
}
